package lib.self.notify;

import com.jakewharton.rxrelay2.PublishRelay;
import com.jakewharton.rxrelay2.Relay;

import io.reactivex.Observable;

/**
 * description:RxBus 用于通信 取代普通的观察者模式
 * author: Steven Xiao
 * date: 2019-11-28
 */
public class RxBus {

    private static volatile RxBus mInstance;

    private final Relay<Object> mBus;

    private RxBus() {
        this.mBus = PublishRelay.create().toSerialized();
    }

    public static RxBus getInstance() {
        if (mInstance == null) {
            synchronized (RxBus.class) {
                if (mInstance == null) {
                    mInstance = Holder.BUS;
                }
            }
        }
        return mInstance;
    }

    public void post(Object object) {
        mBus.accept(object);
    }

    public <T> Observable<T> toObservable(Class<T> tClass) {
        return mBus.ofType(tClass);
    }

    public Observable<Object> toObservable() {
        return mBus;
    }

    public boolean hasObservers() {
        return mBus.hasObservers();
    }

    private static class Holder {
        private static final RxBus BUS = new RxBus();
    }
}
